package com.ingrun.tuboshu.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.stereotype.Component;

import java.sql.Statement;

@Intercepts(value = {@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}), @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}), @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
@Slf4j
@Component
public class PrintSqlInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        long beginTime = System.currentTimeMillis();
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        try {
            return invocation.proceed();
        } finally {
            long endTime = System.currentTimeMillis();
            long costTime = endTime - beginTime;
            BoundSql boundSql = statementHandler.getBoundSql();

            if (costTime > 1500) {
                log.warn("慢SQL语句【{}】，{}，执行耗时：{}ms", boundSql.getSql(), boundSql.getAdditionalParameters(), costTime);
            } else {
                log.info("SQL语句【{}】，{}，执行耗时：{}ms", boundSql.getSql(), boundSql.getAdditionalParameters(), costTime);
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Interceptor.super.plugin(target);
        }

        return target;
    }

}
